# 多阶段构建 Dockerfile
# 第一阶段：构建前端Vue项目
FROM node:16-alpine AS frontend-builder

# 安装必要的工具
RUN apk add --no-cache git

# 设置工作目录
WORKDIR /app/frontend

# 复制前端项目文件
COPY element-admin/package*.json ./
RUN npm install

# 复制前端源码
COPY element-admin/ ./

# 构建前端项目
RUN npm run build:prod

# 第二阶段：构建后端Django应用和最终镜像
FROM python:3.10-slim

# 设置环境变量
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV DJANGO_SETTINGS_MODULE=fs_admin.settings

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    default-libmysqlclient-dev \
    pkg-config \
    nginx \
    supervisor \
    netcat-openbsd \
    curl \
    && rm -rf /var/lib/apt/lists/*

# 创建www-data用户目录
RUN mkdir -p /var/www && chown -R www-data:www-data /var/www

# 设置工作目录
WORKDIR /var/www/backstage-admin

# 复制Django项目依赖文件
COPY fs_admin/requirements.txt ./fs_admin/

# 安装Python依赖
RUN pip install -r fs_admin/requirements.txt
RUN pip install gunicorn

# 复制Django后端代码
COPY fs_admin/ ./fs_admin/

# 从前端构建阶段复制构建产物到正确位置
COPY --from=frontend-builder /app/frontend/dist ./element-admin/dist/

# 创建必要的目录
RUN mkdir -p /var/log/supervisor \
    /var/log/nginx \
    /var/log/gunicorn \
    ./fs_admin/staticfiles \
    ./fs_admin/media \
    ./fs_admin/logs

# 创建配置文件
RUN mkdir -p /etc/supervisor/conf.d

# 创建nginx配置
COPY <<EOF /etc/nginx/sites-available/default
server {
    listen 80;
    server_name _;
    charset utf-8;

    root /var/www/backstage-admin/element-admin/dist;
    index index.html;
    
    location ~* \.(html)$ {
        add_header Cache-Control "no-cache, no-store, must-revalidate";
        add_header Pragma "no-cache";
        add_header Expires "0";
        try_files \$uri \$uri/ /index.html;
    }
    
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files \$uri =404;
    }
    
    location / {
        try_files \$uri \$uri/ /index.html;
    }

    location /prod-api/ {
        proxy_pass http://127.0.0.1:8000/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cookie_flags ~ httponly samesite=lax;
        
        proxy_connect_timeout 10s;
        proxy_send_timeout 10s;
        proxy_read_timeout 10s;
    }

    location /static/ {
        alias /var/www/backstage-admin/element-admin/dist/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files \$uri =404;
    }

    location /django-static/ {
        alias /var/www/backstage-admin/fs_admin/staticfiles/;
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files \$uri =404;
    }

    location /media/ {
        alias /var/www/backstage-admin/fs_admin/media/;
        expires 1y;
        add_header Cache-Control "public";
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
        try_files \$uri =404;
    }

    # 健康检查端点
    location /health/ {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
}
EOF

# 创建supervisor配置
COPY <<EOF /etc/supervisor/conf.d/supervisord.conf
[supervisord]
nodaemon=true
user=root
logfile=/var/log/supervisor/supervisord.log
pidfile=/var/run/supervisord.pid

[program:gunicorn]
command=gunicorn --access-logfile - --workers 3 --bind 127.0.0.1:8000 fs_admin.wsgi:application
directory=/var/www/backstage-admin/fs_admin
user=www-data
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/gunicorn/gunicorn.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=5
environment=DJANGO_SETTINGS_MODULE="fs_admin.settings",PYTHONUNBUFFERED="1",HOME="/tmp"

[program:nginx]
command=nginx -g "daemon off;"
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/nginx/nginx.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=5
EOF

# 创建启动脚本
COPY <<EOF /entrypoint.sh
#!/bin/bash
set -e

# 等待数据库服务（如果需要）
if [ -n "\$DB_HOST" ]; then
    echo "等待数据库连接..."
    while ! nc -z \$DB_HOST \${DB_PORT:-3306}; do
        sleep 1
    done
    echo "数据库连接成功"
fi

# 进入Django项目目录
cd /var/www/backstage-admin/fs_admin

# 数据库迁移
echo "执行数据库迁移..."
python manage.py migrate --noinput

# 收集静态文件
echo "收集静态文件..."
python manage.py collectstatic --noinput

# 创建超级用户（如果设置了环境变量）
if [ -n "\$DJANGO_SUPERUSER_USERNAME" ] && [ -n "\$DJANGO_SUPERUSER_PASSWORD" ] && [ -n "\$DJANGO_SUPERUSER_EMAIL" ]; then
    echo "创建超级用户..."
    python manage.py shell << END
from django.contrib.auth import get_user_model
User = get_user_model()
if not User.objects.filter(username='\$DJANGO_SUPERUSER_USERNAME').exists():
    User.objects.create_superuser('\$DJANGO_SUPERUSER_USERNAME', '\$DJANGO_SUPERUSER_EMAIL', '\$DJANGO_SUPERUSER_PASSWORD')
    print('超级用户创建成功')
else:
    print('超级用户已存在')
END
fi

# 设置正确的文件权限
chown -R www-data:www-data /var/www/backstage-admin/fs_admin/staticfiles
chown -R www-data:www-data /var/www/backstage-admin/fs_admin/media
chown -R www-data:www-data /var/www/backstage-admin/fs_admin/logs

# 启动supervisor
echo "启动应用服务..."
exec supervisord -c /etc/supervisor/conf.d/supervisord.conf
EOF

# 设置启动脚本权限
RUN chmod +x /entrypoint.sh

# 设置正确的文件权限
RUN chown -R www-data:www-data /var/www/backstage-admin

# 暴露端口
EXPOSE 80

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost/health/ || exit 1

# 设置启动命令
ENTRYPOINT ["/entrypoint.sh"] 